package com.wanmait.computershop.dao;

import com.wanmait.computershop.util.DBHelper;
import com.wanmait.computershop.vo.Orderdetle;
import com.wanmait.computershop.vo.Torder;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OrderDAO {

    public static void main(String[] args) {
        List<Torder> torderList = OrderDAO.selectAllByUid(1);
        for(Torder torder : torderList){
            for (int i = 0; i < torder.getOrderdetleList().size(); i++) {
                //System.out.println(torder.getOrderdetleList().get(i).getBNum());
            }
        }
    }

    public static List<Torder> selectAllByUid(Integer uid)
    {
        List<Torder> torderList;
        QueryRunner queryRunner = new QueryRunner(DBHelper.getDruidDataSource());
        String sql = "select *,recv_name recvName,province_name provinceName,city_name cityName,area_name areaName," +
                "detail_name detailName,order_phone orderPhone,order_num orderNum,order_time orderTime," +
                "pay_time payTime from torder where uid = ?";
        try {
            torderList = queryRunner.query(sql,new BeanListHandler<>(Torder.class),uid);
            for(Torder torder : torderList)
            {
                torder.setOrderdetleList(OrderDetleDAO.selectByOid(torder.getId()));
            }
            return torderList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static Torder selectByOrderNum(String orderNum)
    {
        QueryRunner queryRunner = new QueryRunner(DBHelper.getDruidDataSource());
        String sql = "select * from torder where order_num =?";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Torder.class),orderNum);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static void insertOrder(Torder torder)
    {
        QueryRunner queryRunner = new QueryRunner(DBHelper.getDruidDataSource());
        String sql = "insert into torder (uid,recv_name,province_name,city_name,area_name,detail_name,order_phone,order_num) values (?,?,?,?,?,?,?,?)";
        try {
            queryRunner.update(sql, torder.getUid(), torder.getRecvName(), torder.getProvinceName(),
                    torder.getCityName(), torder.getAreaName(), torder.getDetailName(),
                    torder.getOrderPhone(), torder.getOrderNum());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
